/**
 * Author: Zane
 * Email: 873934580@qq.com
 * Date: 2023/5/3
 */
import type { anyObj } from '@/types'
import type { ISystemResponse } from '@/model'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { system } from '@/api'
import { routePathPush } from '@/utils'

export const useSystem = defineStore(
    'system',
    () => {
        const userInfo = ref<ISystemResponse>()
        const tokenValid = (): boolean => {
            return !(userInfo.value === undefined || userInfo.value.token === '')
        }
        const getToken = () => userInfo.value?.token
        const setUserInfo = (data: ISystemResponse) => (userInfo.value = data)
        // 更新用户信息
        const upUserInfo = (data: anyObj) => {
            userInfo.value!.nickname = data.nickname
            userInfo.value!.email = data.email
            userInfo.value!.mobile = data.mobile
        }
        const logout = () => {
            system
                .logout()
                .then(async () => {
                    userInfo.value = undefined
                    await routePathPush('login')
                })
                .catch(() => {})
        }
        return {
            userInfo,
            tokenValid,
            getToken,
            setUserInfo,
            logout,
            upUserInfo,
        }
    },
    {
        persist: {
            enabled: true,
            strategies: [{ storage: sessionStorage, paths: ['userInfo'] }],
        },
    },
)
